package com.yutel.socket;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Listening {

	public static void main(String[] args) {
		ServerSocket ss = null;
		Socket socket = null;
		DataInputStream in = null;
		DataOutputStream out = null;
		try {
			ss = new ServerSocket(50021);
			while (true) {
				socket = ss.accept();
				//接收数据
				in = new DataInputStream(socket.getInputStream());
				int msgLen = in.readInt();
				System.out.println("service size=" + msgLen);
				byte[] data = new byte[msgLen];
				in.readFully(data);
				System.out.println("service msg=" + byte2Str(data));
				//回复数据
				byte[] res="recile".getBytes();
				out = new DataOutputStream(socket.getOutputStream());
				out.writeInt(res.length);
				out.write(res);
				socket.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				ss.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	public static String byte2Str(byte[] bs) {
		StringBuffer sb=new StringBuffer();
		for(byte b:bs){
			sb.append((char)b);
		}
		return sb.toString();
	}
}
